import asyncHandler from "express-async-handler";
import Product from "../models/productModel.js";

//获取所有产品信息
const getProducts = asyncHandler(async (req, res) => {
  //每页展示的产品数量
  const pageSize = 8;
  const page = Number(req.query.pageNumber) || 1;
  //获取keyword
  const keyword = req.query.keyword
    ? // 关键字存在则模糊匹配名称且忽略大小写
      { name: { $regex: req.query.keyword, $options: "i" } }
    : {};

  //获取数据库有多少产品
  const count = await Product.countDocuments({ ...keyword });

  //获取所有产品
  const products = await Product.find({ ...keyword })
    // 分页
    .limit(pageSize)
    //skip()方法用来跳过指定数量的数据
    .skip((page - 1) * pageSize);

  res.json({ products, page, pages: Math.ceil(count / pageSize) });
});

//根据商品id获取商品详情
const getProductById = asyncHandler(async (req, res) => {
  const product = await Product.findById(req.params.id);
  if (product) {
    res.json(product);
  } else {
    res.status(404);
    throw new Error("查询不到这个产品");
  }
});

//删除单个产品
const deleteProduct = asyncHandler(async (req, res) => {
  const product = await Product.findById(req.params.id);
  if (product) {
    await product.remove();
    res.json({ message: "产品删除成功" });
  } else {
    res.status(404);
    throw new Error("查询不到这个产品");
  }
});

//创建产品
const createProduct = asyncHandler(async (req, res) => {
  //创建一个产品模板
  const product = new Product({
    name: "样品名称",
    price: 0,
    user: req.user._id,
    image: "/images/sample.jpg",
    brand: "样品品牌",
    category: "样品分类",
    countInStock: 0,
    numReviews: 0,
    description: "样品描述",
    rating: 0,
  });

  const createdProduct = await product.save();
  res.status(201).json(createdProduct);
});

//更新产品
const updateProduct = asyncHandler(async (req, res) => {
  const {
    name,
    price,
    description,
    image,
    brand,
    category,
    countInStock,
  } = req.body;

  const product = await Product.findById(req.params.id);
  if (product) {
    product.name = name;
    product.price = price;
    product.description = description;
    product.image = image;
    product.brand = brand;
    product.category = category;
    product.countInStock = countInStock;

    const updatedProduct = await product.save();
    res.status(201).json(updatedProduct);
  } else {
    res.status(404);
    throw new Error("查询不到这个产品");
  }
});

//创建产品评论
const createProductReview = asyncHandler(async (req, res) => {
  const { rating, comment } = req.body;

  const product = await Product.findById(req.params.id);
  if (product) {
    //判断用户是否已经评论
    const alreadReviewed = product.reviews.find((review) => {
      review.user.toString() == req.user._id.toString();
    });

    if (alreadReviewed) {
      res.status(400);
      throw new Error("您已经评论过该产品！");
    }

    //创建新评论
    const review = {
      name: req.user.name,
      rating: Number(rating),
      comment,
      user: req.user._id,
    };
    product.reviews.push(review);
    //更新产品的评论数和星星总评价
    product.numReviews = product.reviews.length;
    //对评分进行累加取平均数
    product.rating =
      product.reviews.reduce((acc, review) => acc + review.rating, 0) /
      product.reviews.length;

    await product.save();
    res.status(201).json({ message: "评论成功" });
  } else {
    res.status(404);
    throw new Error("查询不到这个产品");
  }
});

//查找排名前3的产品
const getTopProducts = asyncHandler(async (req, res) => {
  //升序排序取前三
  const products = await Product.find({}).sort({ price: 1 }).limit(3);
  res.json(products);
});

export {
  getProducts,
  getProductById,
  deleteProduct,
  createProduct,
  updateProduct,
  createProductReview,
  getTopProducts,
};
